#!/usr/bin/env python

# Handle email request
# Author : James Tan
# Copyright: "(C) 20012-2013 James Tan. GNU GPL 3."
# Version: v0.2 (beta)

# History (update half a month)
# v0.1  - 11/20/2012
#   basic functionalities
# v0.11 - 01/10/2013  
#  support help, getstockprice commands
#  add support to get any web html and text
# v0.2  - 01/15/2013
#  add VIP service, getstocknewsfeed 

import poplib
from email import parser
from subprocess import call
import StringIO
import time

if __name__ == "__main__":
  pop_conn = poplib.POP3_SSL('pop.gmail.com')
  pop_conn.user('jtan.mailservice')
  pop_conn.pass_('{E4B7DF43-6AE1-47B2-9B4A-5A96A30FC508}')
  #Get messages from server:
  messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
  # Concat message pieces:
  messages = ['\n'.join(mssg[1]) for mssg in messages]
  #Parse message intom an email object:
  messages = [parser.Parser().parsestr(mssg) for mssg in messages]
  for message in messages:
    cmd = message['subject']
    print('Processing email ' + cmd)
    if cmd == 'getalpha' or cmd == 'getweb' or cmd == 'getwebtext':
      for part in message.walk():
        if part.get_content_type() == 'text/plain':
          content = StringIO.StringIO(part.get_payload())  
          lineEnd=1
          totalLine=''
          while 1:
            line = content.readline()
            #print('process line ' + line)
            if not line:
              break
            line = line.strip()
            if lineEnd:  
              if len(totalLine) > 0:
                totalLine=totalLine.replace('=3D','=')
                print('Getting ' + totalLine)
                call(['./'+cmd+'.sh', totalLine])
                call(['./sendemail.sh', message['From']])
                totalLine=''
              if line.startswith( 'http' ):
                if not line.endswith('='):
                  totaline=line
                  lineEnd=1
                else:
                  totalLine=line[:-1]
                  lineEnd=0
            else:
              if not line.endswith('='):
                totalLine+=line
                lineEnd=1
              else:
                totalLine+=line[:-1]
          time.sleep(1)
          break
        else:
          pass
          #print("not a plain text, skip")
    elif cmd == 'help':
      call(['./'+cmd+'.sh'])
      call(['./sendemail.sh', message['From']])
    elif cmd == 'getstocknewsfeed':
      for part in message.walk():
        if part.get_content_type() == 'text/plain':
          content = StringIO.StringIO(part.get_payload())
          while 1:
            line = content.readline()
            #print('process line ' + line)
            if not line:
              break
            line = line.strip()
            if line.startswith( 'SYM:' ):
              print('Getting ' + line)
              call(['./'+cmd+'.sh', line])
              call(['./sendemail.sh', message['From']])
              time.sleep(1)
    elif cmd == 'getstockprice':
      for part in message.walk():
        if part.get_content_type() == 'text/plain':
          content = StringIO.StringIO(part.get_payload())  
          while 1:
            line = content.readline()
            #print('process line ' + line)
            if not line:
              break
            line = line.strip()
            if line.endswith( '.dat' ):
              print('Getting ' + line)
              call(['./'+cmd+'.sh', line])
              call(['./sendemail.sh', message['From']])
              time.sleep(1)
          break
        else:
          pass
          #print("not a plain text, skip")
      
    else:
      print('unknown command')

  pop_conn.quit()
